<?php

namespace yunj;

/**
 * 内部配置
 * Class Config
 * @package yunj
 */
final class Config {

    /**
     * Notes: 获取配置文件所有配置
     * Author: Uncle-L
     * Date: 2021/11/8
     * Time: 21:06
     * @param string[] $path [配置文件地址]
     * @return array
     */
    private static function getFileConfig(array $path): array {
        $config = [];
        foreach ($path as $v)
            if (file_exists($v)) $config += include $v;
        return $config;
    }

    /**
     * Notes: 配置获取
     * Author: Uncle-L
     * Date: 2021/11/8
     * Time: 18:28
     * @param string $key [配置参数名，第一级为配置文件名。支持多级配置 . 号分割且必须。如：admin.title]
     * 获取admin.php的所有配置
     *  admin.
     * 获取admin.php里面的title
     *  admin.title
     * @param null $default [默认值]
     * @param string[] $dir [配置目录]
     * @return mixed
     */
    public static function get(string $key, $default = null, string ...$dir) {
        if (!$dir) $dir = [YUNJ_VENDOR_SRC_PATH . "library/config/"];
        $mark = md5(implode(",", $dir));
        if (!strstr($key, ".")) return $default;
        $keyArr = explode(".", $key);
        // file config
        $fileName = array_shift($keyArr);
        static $config = [];
        if (!isset($config[$mark][$fileName])) {
            $path = [];
            foreach ($dir as $v) $path[] = "{$v}{$fileName}.php";
            $config[$mark][$fileName] = self::getFileConfig($path);
        }
        if (substr($key, -1) === ".") return $config[$mark][$fileName];
        // filterConfig
        $filterConfig = $config[$mark][$fileName];
        foreach ($keyArr as $k) {
            if (isset($filterConfig[$k])) {
                $filterConfig = $filterConfig[$k];
            } else {
                return $default;
            }
        }
        return $filterConfig;
    }

}